package com.course.interceptor;
/*
@author By 林中小鸟
@package  com.self.introduction.component
@create 2021 - 09 - 2021\9\30 0030
@QQ: 357182695
@Em: themooncss@gmail.com
*/

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.course.component.util.HttpContextUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MyInterceptor implements HandlerInterceptor {

    private static final HashMap<String, Object> INFO;

    static {
        INFO = new HashMap<>();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("hasLogin");
        if(user == null && false){
            //notLogin
            request.setAttribute("msg","登陆错误！");
            setReturn(response,400,"用户不存在，请重新登录",INFO);
            return false;
        }else{
            //hasLogin
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

    //返回错误信息
    private static void setReturn(HttpServletResponse response, int status, String msg, Map<String,Object> data) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
        //UTF-8编码
        httpResponse.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        JSONObject json = new JSONObject();
        json.put("code", status);
        json.put("message", msg);
        json.put("data", data);
        String res = JSON.toJSONString(json);
        httpResponse.getWriter().print(res);
    }

}
